package com.garden.rocketmq.learn.demo.producer;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;

/**
 * 同步生产者 发送同步消息
 * 用于注重消息发送可靠性的场景，如短信发送
 * Created by Garden on 2020/7/22.
 */
public class SyncProducer {

    public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException, MQBrokerException {
        //实例化消息生产者Producer
        DefaultMQProducer producer = new DefaultMQProducer("sync_producer_group");
        //设置NameServer的地址，Producer启动后通过NameServer获取目标Topic的路由信息
        producer.setNamesrvAddr("localhost:9876");
        //启动Producer实例
        producer.start();

        //发送消息
        for (int i = 0; i < 100; i++){
            //创建消息，指定主题Topic，标签Tag，业务标识Key，消息体MsgBody [Tag可用于消息过滤，Key可用于消息查询]
            Message msg = new Message("test_topic","sync_producer_tag"
                    ,"sync_producer_key." + i, ("SyncProducer Msg." + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
            //发送消息至Broker
            SendResult sendResult = producer.send(msg);
            //通过发送结果查看是否发送成功
            System.out.printf("%s%n", sendResult);
        }

        //发送完毕，关闭Producer实例
        producer.shutdown();
    }

}
